package com.goktech.olala.client.controller.backstage;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.goktech.olala.client.controller.basic.BasicController;
import com.goktech.olala.client.controller.basic.ResultStatus;
import com.goktech.olala.core.config.SysConfig;
import com.goktech.olala.core.req.ReqGoods;
import com.goktech.olala.core.resp.RespGoodsVo;
import com.goktech.olala.core.service.IGoodsService;
import com.goktech.olala.utils.RMBUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/goodsApi")
public class GoodsController extends BasicController {

    @Autowired
    IGoodsService goodsService;

    /**
     * 商品查询
     *
     * @param request
     * @param sEcho
     * @param iDisplayStart
     * @param iDisplayLength
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryGoodsList.do")
    @ResponseBody
    public ModelMap queryGoodsList(HttpServletRequest request, Integer sEcho,
                                   Integer iDisplayStart, Integer iDisplayLength) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            ReqGoods goodsReq = build(params);

            int pageIndex = iDisplayStart / iDisplayLength+1;
            PageInfo<RespGoodsVo> pageInfo = goodsService.queryGoodsByParam(goodsReq, pageIndex, iDisplayLength);
            if (pageInfo != null && CollectionUtils.isEmpty(pageInfo.getList())) {
                respCode = ResultStatus.QUERY_NULL.getCode();
                respMsg = ResultStatus.QUERY_NULL.getMsg();
            }
            respData = super.respParamsFormat(respCode, respMsg, sEcho, pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = ResultStatus.BAD_REQUEST.getCode();
            respMsg = ResultStatus.BAD_REQUEST.getMsg();
            respData = super.respParamsFormat(respCode, respMsg, null);
        } finally {
            resultMap.put("respData", respData);
            return resultMap;
        }
    }

    /**
     * 根据主键ID查询商品信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryGoodsInfoById.do")
    @ResponseBody
    public ModelMap queryGoodsInfoById(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "";

        JSONObject respData = null;
        try {
            JSONObject params = super.reqParamsFormat(request);
            String goodsId = params.getString("goodsId");

            RespGoodsVo respGoodsVo = goodsService.queryGoodsById(goodsId);
            respData = super.respParamsFormat(respCode, respMsg, respGoodsVo);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = ResultStatus.BAD_REQUEST.getCode();
            respMsg = ResultStatus.BAD_REQUEST.getMsg();
            respData = super.respParamsFormat(respCode, respMsg, null);
        } finally {
            resultMap.put("respData", respData);
            return resultMap;
        }
    }

    /**
     * 商品删除
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/removeGoodsById.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap removeGoodsById(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "删除成功";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            String goodsId = params.getString("goodsId");

            int result = goodsService.removeGoodsById(goodsId);
            respData = super.respParamsFormat(respCode,respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respData = super.respParamsFormat(SysConfig.ERROR_CODE,"服务异常", null);
        } finally {
            resultMap.put("respData", respData);
            return resultMap;
        }
    }

    /**
     * 商品上/下架
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateGoodsIsOnById.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap updateGoodsIsOnById(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = SysConfig.SUCCESS_CODE;
        String respMsg = "";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            String goodsId = params.getString("goodsId");
            Integer isOnSale = params.getInteger("isOnSale");

            int result = goodsService.updateGoodsIsOnById(goodsId, isOnSale);
            respData = super.respParamsFormat(respCode,respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respData = super.respParamsFormat(SysConfig.ERROR_CODE,"服务异常", null);
        } finally {
            resultMap.put("respData", respData);
            return resultMap;
        }
    }


    /**
     * 保存商品信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveGoodsInfo.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap saveGoodsInfo(HttpServletRequest request) {

        ModelMap resultMap = new ModelMap();
        Integer respCode = ResultStatus.SUCCESS.getCode();
        String respMsg = ResultStatus.SUCCESS.getMsg();

        JSONObject respData = null;
        try {
            JSONObject params = super.reqParamsFormat(request);
            ReqGoods goodsReq = build(params);

            int result = goodsService.saveGoodsInfo(goodsReq);
            respData = super.respParamsFormat(respCode, respMsg, result);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = ResultStatus.BAD_REQUEST.getCode();
            respMsg = ResultStatus.BAD_REQUEST.getMsg();
            respData = super.respParamsFormat(respCode, respMsg, null);
        } finally {
            resultMap.put("respData", respData);
            return resultMap;
        }
    }


    /**
     * 构建查询实体类
     *
     * @param params
     * @return
     */
    private ReqGoods build(JSONObject params) {
        ReqGoods reqGoods = new ReqGoods();

        String goodsId = params.getString("goodsId");
        String goodsName = params.getString("goodsName");
        String goodsTitle = params.getString("goodsTitle");
        String goodsBrief = params.getString("goodsBrief");
        String keywords = params.getString("keywords");
        String catyId = params.getString("catyId");
        String businessSn = params.getString("businessSn");
        String effectiveDate = params.getString("effectiveDate");
        Integer expiryDays = params.getInteger("expiryDays");
        Integer discount = params.getInteger("discount");
        String shopPrice = params.getString("shopPrice");
        String marketPrice = params.getString("marketPrice");
        String costPrice = params.getString("costPrice");
        String promotePrice = params.getString("promotePrice");
        String promoteStartDate = params.getString("promoteStartDate");
        String promoteEndDate = params.getString("promoteEndDate");
        Integer isOnSale = params.getInteger("isOnSale");
        Integer sortOrl = params.getInteger("sortOrl");
        String isComment = params.getString("isComment");
        String goodsDesc = params.getString("goodsDesc");
        String beginTime = params.getString("beginTime");
        String endTime = params.getString("endTime");
        String imgPathArr = params.getString("imgPathArr");
        String extendsJson = params.getString("extendsJson");
        //商品参数信息
        Integer brandId = params.getInteger("brandId");
        String specs = params.getString("specs");
        String weight = params.getString("weight");
        String produceAddr = params.getString("produceAddr");
        String ingredients = params.getString("ingredients");
        String sourceSupplier = params.getString("sourceSupplier");
        String color = params.getString("color");
        String eatMethod = params.getString("eatMethod");
        String size = params.getString("size");
        Integer isAloneSale = params.getInteger("isAloneSale");
        Integer isBest = params.getInteger("isBest");
        String packageType = params.getString("packageType");
        String storageType = params.getString("storageType");
        String sourceAddr = params.getString("sourceAddr");
        Integer integral = params.getInteger("integral");
        String proLicenseNo = params.getString("proLicenseNo");
        Integer giveIntegral = params.getInteger("giveIntegral");

        reqGoods.setGoodsId(goodsId);
        reqGoods.setGoodsName(goodsName);
        reqGoods.setGoodsTitle(goodsTitle);
        reqGoods.setGoodsBrief(goodsBrief);
        reqGoods.setKeywords(keywords);
        reqGoods.setCatyId(catyId);
        reqGoods.setBusinessSn(businessSn);
        reqGoods.setExpiryDays(expiryDays);
        reqGoods.setImgPathArr(imgPathArr);
        reqGoods.setExtendsJson(extendsJson);

        if(StringUtils.isNotBlank(costPrice)){
            reqGoods.setCostPrice(Integer.parseInt(RMBUtil.changeY2F(costPrice)));
        }

        if(StringUtils.isNotBlank(marketPrice)){
            reqGoods.setMarketPrice(Integer.parseInt(RMBUtil.changeY2F(marketPrice)));
        }
        if(StringUtils.isNotBlank(shopPrice)){
            reqGoods.setShopPrice(Integer.parseInt(RMBUtil.changeY2F(shopPrice)));
        }
        if(StringUtils.isNotBlank(promotePrice)){
            reqGoods.setPromotePrice(Integer.parseInt(RMBUtil.changeY2F(promotePrice)));
        }

        reqGoods.setEffectiveDate(effectiveDate);
        reqGoods.setDiscount(discount);
        reqGoods.setPromoteEndDate(promoteEndDate);
        reqGoods.setPromoteStartDate(promoteStartDate);
        reqGoods.setIsOnSale(isOnSale);
        reqGoods.setSortOrl(sortOrl);
        reqGoods.setIsComment("on".equals(isComment)?1:0);
        reqGoods.setGoodsDesc(goodsDesc);
        reqGoods.setBeginTime(beginTime);
        reqGoods.setEndTime(endTime);

        reqGoods.setBrandId(brandId);
        reqGoods.setSpecs(specs);
        if(StringUtils.isNotBlank(weight)){
            reqGoods.setWeight(Integer.parseInt(RMBUtil.changeY2F(weight)));
        }
        reqGoods.setProduceAddr(produceAddr);
        reqGoods.setIngredients(ingredients);
        reqGoods.setSourceSupplier(sourceSupplier);
        reqGoods.setColor(color);
        reqGoods.setEatMethod(eatMethod);
        reqGoods.setSize(size);
        reqGoods.setIsAloneSale(isAloneSale);
        reqGoods.setIsBest(isBest);
        reqGoods.setPackageType(packageType);
        reqGoods.setStorageType(storageType);
        reqGoods.setSourceAddr(sourceAddr);
        reqGoods.setProLicenseNo(proLicenseNo);
        reqGoods.setIntegral(integral);
        reqGoods.setGiveIntegral(giveIntegral);

        return reqGoods;
    }
}
